<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小企业物联网转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82282996  15899929162
// +----------------------------------------------------------------------
namespace app\common\repositories\system\sms;

use app\common\dao\system\sms\SystemSmsConfigDao;
use app\common\repositories\BaseRepository;
use app\common\repositories\property\users\PropertyUsersLogRepository;
use app\common\services\CacheService;
use think\facade\Db;

/**
 * Class SystemSmsConfigRepository
 *
 * @mixin SystemSmsConfigDao
 */
class SystemSmsConfigRepository extends BaseRepository
{

    public function __construct(SystemSmsConfigDao $dao)
    {
        $this->dao = $dao;
    }

    public function addInfo(array $data, int $propertyId = 1, int $userId = 0)
    {
        return Db::transaction(function () use ($data, $propertyId, $userId) {
            $data['property_id'] = $propertyId;
            $info = $this->create($data);
            return $info;
        });
    }

    public function editInfo($info, array $data, int $userId = 0)
    {
        return Db::transaction(function () use ($data, $info, $userId) {
            $res = $this->update($info['id'], $data);

            /** @var PropertyUsersLogRepository $repository */
            $repository = app()->make(PropertyUsersLogRepository::class);
            $repository->addInfo($info['id'], $userId, 'SMS.CONFIG.EDIT', $data);
            return $res;
        });
    }

    public function getConfig(int $propertyId)
    {
        return CacheService::create($propertyId)->remember('property_sms_config_' . $propertyId, function () use ($propertyId) {
            $res = $this->dao->getSearch([])
                ->where('property_id', $propertyId)
                ->find();
            if ($res) {
                return $res->toArray();
            }
            return $res;
        }, 86400);
    }
}